// 业务类

/**
 * 构造方法
 * @param _parent 父容器实例对象或者id字符串
 * @param _data 要渲染的业务数据
 * @param _isSingle 是否是作为独立的画布渲染，默认为true；嵌入到其他SVG容器中时，设置为false
 * @param _attrs 顶层容器属性对象
 */
var Biz = function(_parent, _data, _isSingle, _attrs) {

    // --------------------------------------------------------------------------
    // import
    // --------------------------------------------------------------------------
	
	const SceneConst = room2d.sceneConst;
	const ObjectUtil = ghca_charts.view.util.objectUtil;
	const ElementUtil = ghca_charts.view.util.elementUtil;
	const EvEvent = room2d.events.evEvent;
	const EventUtil = ghca_charts.view.util.eventUtil;
	const Loading = room2d.view.component.loading;
	const App = room2d.app;
	
	//参数检测    
    if (arguments.length < 1) {
        throw new Error('传入参数个数错误,当前个数' + arguments.length + ",需要传入前1个参数。");
    }
    //若不传，则默认为单独渲染的一个canvas
    if(arguments.length < 3) {
        _isSingle = true;
    }
    
	var self = this;
	var isLoaded = true;
	var _configMap = {};
	var scaleSize = 100;
	var loading;
	
	// --------------------------------------------------------------------------
    //
    // Attributes
    //
    // --------------------------------------------------------------------------
	
	// ------------------------------
    // roomCode
    // ------------------------------

    /**
     * 房间号
     */
    var roomCode = null;
    this.roomCode = function(value) {
        if (!arguments.length) {
            return roomCode;                
        }
        roomCode = value;
        return this;
    };
    
    // ------------------------------
    // data
    // ------------------------------

    /**
     * 业务数据
     */
    var data = _data;
    this.data = function(value) {
        if (!arguments.length) {
            return data;                
        }
        data = value;
        return this;
    };
    
    // ------------------------------
    // parent
    // ------------------------------

    /**
     * 父容器
     */
    var parent = _parent;
    this.parent = function(value) {
        if (!arguments.length) {
            return parent;                
        }
        parent = value;
        return this;
    };
    
    // ------------------------------
    // sceneRenderer
    // ------------------------------

    /**
     * 场景渲染器实例
     */
    var sceneRenderer = null;
    this.sceneRenderer = function(value) {
        if (!arguments.length) {
            return sceneRenderer;                
        }
        sceneRenderer = value;
        return this;
    };
    
//    // ------------------------------
//    // sourcePath
//    // ------------------------------
//
//    /**
//     * 资源路径
//     */
//    var sourcePath = App.isDebug ? "../" : "";
//    this.sourcePath = function(value) {
//        if (!arguments.length) {
//            return sourcePath;                
//        }
//        sourcePath = value;
//        return this;
//    };
    
    // ------------------------------
    // apiPath
    // ------------------------------

    /**
     * api路径
     */
    var apiPath;
    try {
       apiPath = App.isDebug ? "http://192.168.187.10:8080/oss" : window.parent.ev_room2d_interface_getParams().host;
    } catch(e) {
        console.log(e);
    }
    this.apiPath = function(value) {
        if (!arguments.length) {
            return apiPath;                
        }
        apiPath = value;
        return this;
    };
    
    // --------------------------------------------------------------------------
    //
    // public methods
    //
    // --------------------------------------------------------------------------
	
	this.create = function() {
		if(!isLoaded) {
			return;
		}
		//解析配置
		parseConfig(self.data().bizConfig);
		//根据配置和机房数据获取最终渲染数据
		var roomData = getRoomData();
		//渲染内容
		var graph = new ghca_charts.view.graph(self.parent(), roomData);
        graph.render();
        //若为嵌入界面
        if(!_isSingle) {
        	//则重新设置房间尺寸和位置，等比缩放房间，以适合外层父容器的尺寸
        	var roomChart = graph.getChildChart().mainContainer();
            var fitScale = setFitScaleAndMoveCenter(roomChart);
            var topCon = graph.topComponent.mainContainer();
            if(ObjectUtil.isObject(_attrs)) {
                _attrs.width /= fitScale;
                _attrs.height /= fitScale;
                ElementUtil.setElementProperties(topCon, _attrs);
            }
            
            //移除mousedown监听，否则鼠标点击机房时，外层平面图无法拖动
            graph.getChildChart().children()[0].removeDragListeners();
        }
        //隐藏等待界面
        visibleLoading(false);
	};
	
	// --------------------------------------------------------------------------
    //
    // listeners
    //
    // --------------------------------------------------------------------------
	
	var data_changeHandler = function(event) {
		event.stopPropagation();
		var detail = event.detail;
		if(detail.length < 2) {
            alert("机房初始化数据为空。");
            visibleLoading(false);
            return;
        }
        //根据初始化数据初始化场景内容
        self.data({bizConfig:detail[0], bizData:detail[1]});
        self.create();
	};
	
    // --------------------------------------------------------------------------
    //
    // private methods
    //
    // --------------------------------------------------------------------------
	
	var init = function() {
		//父容器检测
        if (typeof(_parent) == 'string') {
            _parent = document.getElementById(_parent);
        }
        if (_parent) {
            self.parent(_parent);
        } else {
            throw new Error('_parent构造方法中传入的容器_parent:' + _parent + "无法找到。");
        }
        
        //通知外部引擎初始化完毕
		if(_isSingle) {
			noticeStageInitSuccess();
		}
		addListeners();
		
		if(ObjectUtil.isString(_data)) {
			self.roomCode(_data);
			self.data(null);
		}
		if(!_isSingle && !self.data()) {
			isLoaded = false;
			loadRoomConfig();
		}
	};
	
	var addListeners = function() {
		//这里不用renderDom注册监听，是因为此时renderDom尚未实例化
        self.parent().addEventListener(EvEvent.EV_DATA_CHANGED, data_changeHandler);
    };
	
	//通知外部引擎初始化完毕    
    var noticeStageInitSuccess = function() {
        visibleLoading(true, "初始化...");
        var e = EventUtil.createCustomEvent(EvEvent.EV_STAGE_INIT_SUCCESS, false, false);
        EventUtil.dispatchEvent(self.parent(), e);
    };
    
    var visibleLoading = function(visible, content) {
    	if(!loading) {
            loading = new Loading(self.parent(), content);
        } else {
        	loading.content(content);
            loading.visible(visible);
        }
    };
	
    // --------------------------------------------------------------------------
    // load and parse biz config and data methods
    // --------------------------------------------------------------------------
	
	var parseBizConfig = function(data) {
        var childrens = [];
        for(var i=0,len=data.length; i<len; i++){    //转换规格实例数组给视图
            childrens = childrens.concat(data[i].children);
        }
        return childrens;
    };
    
    var parseBizData = function(data) {
        return data;
    };
    
    var parseConfig = function(config) {
        if(!ObjectUtil.isArray(config) || config.length === 0) {
            return;
        }
        for (var item, key, i = 0, len = config.length; i < len; i++) {
            item = config[i];
            key = getConfigMapKey(item);
            _configMap[key] = item;
        }
    };
    
    var getConfigMapKey = function(item) {
        if(!item) {
            return null; 
        }
        var key;
//        if(item.type === SceneConst.OBJECT_TYPE_JIJIA || item.type === SceneConst.OBJECT_TYPE_YUZHANJIGUI) {
//            key = item.type + SceneConst.CONNECTOR + item.dataKey + SceneConst.CONNECTOR + item.sideType;
//        } else if(item.type === SceneConst.OBJECT_TYPE_LIETOUGUI) {
//            key = item.dataKey ? (item.type + SceneConst.CONNECTOR + item.dataKey) : item.type;
//        } else {
            key = item.type;
//        }
        return key;
    };
	
	var loadRoomConfig = function() {
        var errorMsg = "加载房间配置错误。";
        $.ajax({
            type: 'GET',
            url: apiPath + "/graphData/getRoomMenuList",
            data: {roomCode:self.roomCode()},
            error: function() {
                alert(errorMsg);
            },
            success: function(result) {
                if(!result) {
                    alert(errorMsg);
                } else {
                	if(ObjectUtil.isString(result)) {
                		result = JSON.parse(result);
                	}
                	if(!self.data()) {
                		self.data({})
                	}
                	self.data().bizConfig = parseBizConfig(result);
                	loadRoomData(self.roomCode());
                }
            }
        });
    };
    
    var loadRoomData = function(roomCode) {
        var errorMsg = "加载房间信息错误。";
        $.ajax({
            type: 'GET',
            url: apiPath + "/graphData/getRoomAll",
            data: {roomCode:roomCode},
            error: function() {
                alert(errorMsg);
            },
            success: function(result) {
                if(!result) {
                    alert(errorMsg);
                } else {
                	if(ObjectUtil.isString(result)) {
                        result = JSON.parse(result);
                    }
                    isLoaded = true;
                    if(!self.data()) {
                        self.data({})
                    }
                    self.data().bizData = parseBizData(result);
                    self.create();
                }
            }
        });
    };
    
    // --------------------------------------------------------------------------
    // create render data methods
    // --------------------------------------------------------------------------
    
    var getRoomData = function() {
    	var bizData = self.data().bizData;
    	bizData.floorRow = Math.ceil(bizData.roomWidth / SceneConst.TILE_LONG);
        bizData.floorCol = Math.ceil(bizData.roomLength / SceneConst.TILE_WIDTH);
        const floorRow = parseInt(bizData["floorRow"]);
        const floorCol = parseInt(bizData["floorCol"]);
        const floorW = floorCol * SceneConst.TILE_LONG;
        const floorH = floorRow * SceneConst.TILE_WIDTH; 
        const halfFloorW = floorW / 2;
        const halfFloorH = floorH / 2;
        const roomW = floorW * scaleSize;
        const roomH = floorH * scaleSize;
        const jijiaW = getNumber(_configMap[SceneConst.OBJECT_TYPE_JIJIA].length/1000) * scaleSize;
        const jijiaH = getNumber(_configMap[SceneConst.OBJECT_TYPE_JIJIA].width/1000) * scaleSize;
        const ltdW = getNumber(_configMap[SceneConst.OBJECT_TYPE_LENGTONGDAO].length/1000) * scaleSize;
        const ltdH = getNumber(_configMap[SceneConst.OBJECT_TYPE_LENGTONGDAO].width/1000) * scaleSize;
        const ltgW = getNumber(_configMap[SceneConst.OBJECT_TYPE_LIETOUGUI].length/1000) * scaleSize;
        const ltgH = getNumber(_configMap[SceneConst.OBJECT_TYPE_LIETOUGUI].width/1000) * scaleSize;
        const lizhuW = getNumber(_configMap[SceneConst.OBJECT_TYPE_ZHUZI].length/1000) * scaleSize;
        const lizhuH = getNumber(_configMap[SceneConst.OBJECT_TYPE_ZHUZI].width/1000) * scaleSize;
        
        var data = {
            width:roomW,
            height:roomH,
            autoResize:false,
            background:_isSingle ? {fill:SceneConst.BACKGROUND_COLOR } : {fill:SceneConst.BACKGROUND_COLOR, style:"pointer-events:none;"},
            //border:{stroke:"black", "stroke-width":1},
            type:"chart",
            legend:{
                xPos:"left",
                yPos:"top",
                keyPath : "data",
                key:"biz_state",
                labelFormat:"{#" +
                		"switch(d.biz_state) {" +
                		"case SceneConst.CUS_BIZ_STATE_ONE:SceneConst.CUS_BIZ_STATE_ONE_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_TWO:SceneConst.CUS_BIZ_STATE_TWO_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_THREE:SceneConst.CUS_BIZ_STATE_THREE_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_FOUR:SceneConst.CUS_BIZ_STATE_FOUR_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_FIVE:SceneConst.CUS_BIZ_STATE_FIVE_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_SIX:SceneConst.CUS_BIZ_STATE_SIX_INTRO; break;" +
                		"case SceneConst.CUS_BIZ_STATE_SEVEN:SceneConst.CUS_BIZ_STATE_SEVEN_INTRO; break;" +
                		"default:SceneConst.CUS_BIZ_STATE_UNKNOWN_INTRO; break;}" +
                		"#}",
//                items:[
//                    SceneConst.CUS_BIZ_STATE_ONE,
//                    SceneConst.CUS_BIZ_STATE_TWO,
//                    SceneConst.CUS_BIZ_STATE_THREE,
//                    SceneConst.CUS_BIZ_STATE_FOUR,
//                    SceneConst.CUS_BIZ_STATE_FIVE,
//                    SceneConst.CUS_BIZ_STATE_SIX,
//                    SceneConst.CUS_BIZ_STATE_SEVEN
//                ],
                colors:[
                    SceneConst.CUS_BIZ_STATE_ONE_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_TWO_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_THREE_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_FOUR_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_FIVE_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_SIX_BLEND_COLOR,
                    SceneConst.CUS_BIZ_STATE_SEVEN_BLEND_COLOR
                ],
                domain:[
                    SceneConst.CUS_BIZ_STATE_TWO,
                    SceneConst.CUS_BIZ_STATE_THREE,
                    SceneConst.CUS_BIZ_STATE_FOUR,
                    SceneConst.CUS_BIZ_STATE_FIVE,
                    SceneConst.CUS_BIZ_STATE_SIX,
                    SceneConst.CUS_BIZ_STATE_SEVEN
                ],
                label : {
                    "fill" : "#fff",
                    "font-siz" : "12",
                    "font-family" : "Microsoft YaHei"
                },
                mouseOverEffect:true,
                showTotal:true,
                visible:true
            },
//            toolTip:{
//                trigger:"item",//触发条件，值可为xAxis|yAxis|item
//                labelFormat:"{#d.info#}"//标签内容格式
//            },
            series:[
                {
                	type:"room",
                    width:roomW,
                    height:roomH,
                    scaleType:_isSingle ? 0 : -1,
                    dragable:_isSingle,
                    renderers:{
                    	"1":{//机架
                            "clazz" : "node",
                            "config" : {
                                "main" : {
                                    "clazz" : "jiguiNode",
                                    "config" : {
                                        "imageWidth" : "{width}",
                                        "imageHeight" : "{height}",
                                        "opacity" : 1,
                                        "url" : "{url}",
                                        "title": "{info}",
                                        "background" : {
                                            "x" : -jijiaH/2,
                                            "y" : -jijiaH/2,
                                            "width" : jijiaH,
                                            "height" : jijiaH,
                                            "color" : "{legendColor}"
                                        }
                                    }
                                },
                                "backGround" : {
                                    "clazz" : "rect",
                                    "config" : {
                                        "x" : -jijiaW/2,
                                        "y" : -jijiaH/2,
                                        "width" : "{width}",
                                        "height" : "{height}",
                                        "border" : 1,
                                        "borderColor" : "#ff7f0e",
                                        "linecap" : "butt",
                                        "color" : "none"
                                    }
                                },
                                "label" : {
                                    "clazz" : "label",
                                    "rotate" : "0",
                                    "position" : "center",
                                    "gap" : 0,
                                    "config" : {
                                        "text" : "{name}",
                                        "maxWidth" : 100,
                                        "backGroundColor" : "none",
                                        "backGroundOpacity" : 0,
                                        "borderRadius" : 4,
                                        "padding" : 0,
                                        "fontColor" : "#ffffff",
                                        "fontFamily" : "Microsoft YaHei",
                                        "fontSize" : 12,
                                        "textLine" : 1,
                                        "visible" : true
                                    }
                                }
                            }
                        },
                        "3":{//冷通道
                            "clazz" : "node",
                            "config" : {
                                "main" : {
                                    "clazz" : "imageNode",
                                    "config" : {
                                        "imageWidth" : "{width}",
                                        "imageHeight" : "{height}",
                                        "opacity" : 1,
                                        "url" : "{url}"
                                    }
                                },
                                "backGround" : {
                                    "clazz" : "rect",
                                    "config" : {
                                        "x" : -ltdW/2,
                                        "y" : -ltdH/2,
                                        "width" : "{width}",
                                        "height" : "{height}",
                                        "border" : 1,
                                        "borderColor" : "#ff7f0e",
                                        "linecap" : "butt",
                                        "color" : "none"
                                    }
                                }
                            }
                        },
                        "6":{//列头柜
                            "clazz" : "node",
                            "config" : {
                                "main" : {
                                    "clazz" : "imageNode",
                                    "config" : {
                                        "imageWidth" : "{width}",
                                        "imageHeight" : "{height}",
                                        "opacity" : 1,
                                        "url" : "{url}"
                                    }
                                },
                                "backGround" : {
                                    "clazz" : "rect",
                                    "config" : {
                                        "x" : -ltgW/2,
                                        "y" : -ltgH/2,
                                        "width" : "{width}",
                                        "height" : "{height}",
                                        "border" : 1,
                                        "borderColor" : "#ff7f0e",
                                        "linecap" : "butt",
                                        "color" : "none"
                                    }
                                }
                            }
                        },
                        "8":{//立柱
                            "clazz" : "node",
                            "config" : {
                                "main" : {
                                    "clazz" : "imageNode",
                                    "config" : {
                                        "imageWidth" : "{width}",
                                        "imageHeight" : "{height}",
                                        "opacity" : 1,
                                        "url" : "{url}"
                                    }
                                },
                                "backGround" : {
                                    "clazz" : "rect",
                                    "config" : {
                                        "x" : -lizhuW/2,
                                        "y" : -lizhuH/2,
                                        "width" : "{width}",
                                        "height" : "{height}",
                                        "border" : 1,
                                        "borderColor" : "#ff7f0e",
                                        "linecap" : "butt",
                                        "color" : "none"
                                    }
                                }
                            }
                        }
                    },
                    data:[
                    ]
                }
            ]
        };
        
        var roomData = data.series[0].data;
        var bizDataItems = bizData.data;
        for (var bizItem, item, config, i = 0, len = bizDataItems.length; i < len; i++) {
        	bizItem = bizDataItems[i];
        	config = _configMap[getConfigMapKey(bizItem)];
        	item = {};
        	item.bizData = bizItem;
        	item.id = bizItem.id;
        	item.renderer = String(bizItem.type);
        	item.type = bizItem.type;
        	if(item.type === SceneConst.OBJECT_TYPE_JIJIA) {
        		item.url = "../image/jigui/jigui.svg";
        		item.biz_state = getNumber(bizItem.biz_state, SceneConst.CUS_BIZ_STATE_ONE);
        	} else if(item.type === SceneConst.OBJECT_TYPE_LENGTONGDAO) {
                item.url = "../image/lengtongdao/ltd.svg";
            } else if(item.type === SceneConst.OBJECT_TYPE_LIETOUGUI) {
                item.url = "../image/PDU/top.svg";
            } else if(item.type === SceneConst.OBJECT_TYPE_ZHUZI) {
                item.url = "../image/pillar/top.png";
            } else {
            	item.url = config.source;
            }
        	item.info = bizItem.info;
        	item.name = ObjectUtil.isString(bizItem.name) ? bizItem.name : config.name;
            item.x = (getNumber(bizItem.tx) + halfFloorW) * scaleSize;
            item.y = (getNumber(bizItem.tz) + halfFloorH) * scaleSize;
            item.width = getNumber(config.length/1000) * scaleSize;
            item.height = getNumber(config.width/1000) * scaleSize;
            parseBizStateEffect(item);
        	roomData.push(item);
        }
        
        return data;
    };
    
    var parseBizStateEffect = function(item) {
        var color;
        //item.biz_state = Math.floor(8*Math.random());
        switch(item.biz_state) {
            case SceneConst.CUS_BIZ_STATE_ONE:
                color = SceneConst.CUS_BIZ_STATE_ONE_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_TWO:
                color = SceneConst.CUS_BIZ_STATE_TWO_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_THREE:
                color = SceneConst.CUS_BIZ_STATE_THREE_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_FOUR:
                color = SceneConst.CUS_BIZ_STATE_FOUR_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_FIVE:
                color = SceneConst.CUS_BIZ_STATE_FIVE_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_SIX:
                color = SceneConst.CUS_BIZ_STATE_SIX_BLEND_COLOR;
                break;
            case SceneConst.CUS_BIZ_STATE_SEVEN:
                color = SceneConst.CUS_BIZ_STATE_SEVEN_BLEND_COLOR;
                break;
            default:
                color = SceneConst.CUS_BIZ_STATE_ONE_BLEND_COLOR;
                break;
        }
        item.color = color;
    };
    
    // --------------------------------------------------------------------------
    // util methods
    // --------------------------------------------------------------------------
    
    var getNumber = function(data, defaultVal) {
    	isNaN(defaultVal) && (defaultVal = 0);
        return isNaN(data) ? defaultVal : Number(data);
    };
    
    var setFitScaleAndMoveCenter = function(roomChart) {
        var bizData = self.data().bizData;
        const conW = _attrs.width;
        const conH = _attrs.height;
        const floorRow = parseInt(bizData["floorRow"]);
        const floorCol = parseInt(bizData["floorCol"]);
        const floorW = floorCol * SceneConst.TILE_LONG * scaleSize;
        const floorH = floorRow * SceneConst.TILE_WIDTH * scaleSize;
        var fitScale = 1;
        if(floorW > conW || floorH > conH) {
            var sw = conW/floorW;
            var sh = conH/floorH;
            fitScale = sw < sh ? sw : sh;
        }
        var tx = (conW - floorW * fitScale) / 2 ;
        var ty = (conH - floorH * fitScale) / 2 ;
        roomChart.attr("transform", "translate(" + [tx, ty] + ")scale(" + [fitScale, fitScale] + ")");
        return fitScale;
    };
    
    var addPorperty = function(target, pName, key, value) {
        if(!target) {
            return;
        }
        if(!ObjectUtil.isObject(target[pName])) {
            target[pName] = {};
        }
        target[pName][key] = value;
    };
    
    //run function
	init();
};

Biz.struct = function(room2d) {
    Biz.prototype.constructor = Biz;
};

module.exports = Biz;